package com.foruo.modules.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foruo.modules.demo.entity.DemoEntity;
import com.foruo.modules.demo.service.DemoService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 模拟controller
 * 返回Json格式数据
 * @author GaoYuan
 * @date 2018/5/10 下午3:24
 */
public class DemoJsonServlet extends HttpServlet{

    DemoService demoService = new DemoService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        try {
            String id = request.getParameter("id");
            DemoEntity demoEntity = demoService.get(id);
            PrintWriter out = response.getWriter();
            JSONObject jsonObject = (JSONObject) JSON.toJSON(demoEntity);
            out.println(jsonObject);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

}
